package com.web.imp;

import com.web.annotations.PageUrl;
import com.web.lang.LanguageConfig;
import com.web.model.PageBrowser;
import com.web.model.PageFactory;
import com.web.model.WebPage;

public class PageFactoryImp implements PageFactory{

	private String host;
	
	public PageFactoryImp(String host){
		
		this.host = host;
	}
	
	public <T extends WebPage> T newPage(Class<T> pageClass, PageBrowser browser){
		
		LanguageConfig.initCopies(pageClass);
		
		AbstractWebPage pageInstance = tryNewPageInstance(pageClass);

		if(pageClass.isAnnotationPresent(PageUrl.class)){
			
			PageUrl annotationUrl = pageClass.getAnnotation(PageUrl.class);
		
			String url = host + annotationUrl.value();
			
			pageInstance.setUrl(url);
		}
		
		pageInstance.setBrowser(browser);
		
		@SuppressWarnings("unchecked")
		T page = (T) pageInstance;
		
		return page;
	}
	
	private <T extends WebPage> AbstractWebPage tryNewPageInstance(Class<T> pageClass){
		
		try {
			AbstractWebPage pageInstance = (AbstractWebPage) pageClass.newInstance();
			return pageInstance;
			
		} catch (Exception e) {
			throw new IllegalStateException(String.format("Page class must have constructor '%s()'", pageClass.getSimpleName()), e);
		}
	}
}
